package analysis

import (
	"fmt"
	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/orm"
	"github.com/gogf/gf/os/gcache"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/util/gconv"
	"time"
)

var visitCache *gcache.Cache

func init() {
	visitCache = gcache.New()
}

type SiteVisit struct {
	Id      int
	Address string    `orm:"size(32);index"`
	Path    string    `orm:"size(128);index"`
	Date    time.Time `orm:"type(datetime);index"`
}

func (o *SiteVisit) TableName() string {
	return "blog_analysis_site_visit_log"
}

var VisitLogFilter = func(ctx *context.Context) {
	address := ctx.Input.Header("X-Read-IP")
	if address == "" {
		address = ctx.Input.IP()
	}
	key := fmt.Sprintf("%s_%s", address, ctx.Request.RequestURI)
	if !visitCache.Contains(key) {
		visitCache.Set(key, true, time.Minute*30)
		go CreateVisitLog(address, ctx.Request.RequestURI)
	}
}

func CreateVisitLog(address, path string) {
	log := SiteVisit{Address: address, Path: path, Date: time.Now()}
	_, _ = orm.NewOrm().Insert(&log)
}

func GetToDayVisitCount() int64 {
	today := time.Now().Format("2006-01-02")
	sql := fmt.Sprintf("select count(distinct address) as count from blog_analysis_site_visit_log where date like '%s%%'", today)
	var maps []orm.Params
	_, err := orm.NewOrm().Raw(sql).Values(&maps)
	if err != nil {
		glog.Error(err)
		return 0
	}
	return gconv.Int64(maps[0]["count"])
}
